﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using Infragistics.WebUI.UltraWebGrid;
using uMES.LeanManufacturing.Common;
using System.IO;
using uMES.LeanManufacturing.ReportBusiness;
using uMES.LeanManufacturing.ParameterDTO;
using System.Text;
using System.Text.RegularExpressions;
using uMES.LeanManufacturing.DBUtility;
using System.Drawing;
using System.Data.OracleClient;
using CamstarAPI;
public partial class uMESContainerMoverNonStdForm : System.Web.UI.Page, INormalReport
{
    const string QueryWhere = "uMESContainerMoverNonStdForm";
    uMESCommonBusiness common = new uMESCommonBusiness();
    uMESPartReportingBusiness bll = new uMESPartReportingBusiness();
    uMESContainerBusiness bll1 = new uMESContainerBusiness();
    string businessName = "批次管理", parentName = "Container";

    protected void Page_Load(object sender, EventArgs e)
    {
        uMESMasterPage master = this.Master as uMESMasterPage;
        master.strNavigation = "当前位置：工艺变更";
        master.strTitle = "工艺变更";
        master.ChangeFrame(true);
        NormalReportControl normalCntrl = new NormalReportControl();
        normalCntrl.LtnFirst = lbtnFirst;
        normalCntrl.LtnLast = lbtnLast;
        normalCntrl.LtnNext = lbtnNext;
        normalCntrl.LtnPrev = lbtnPrev;
        normalCntrl.BtnReset = btnReSet;
        normalCntrl.BtnGo = btnGo;
        normalCntrl.BtnSearch = btnSearch;
        normalCntrl.LabPages = lLabel1;
        normalCntrl.TxtPage = txtPage;
        normalCntrl.TxtTotalPage = txtTotalPage;
        normalCntrl.TxtCurrentPage = txtCurrentPage;
        normalCntrl.NormalOperation = this;
        normalCntrl.QueryWhere = QueryWhere;

        if (!IsPostBack)
        {
            //ShowStatusMessage("", true);
            ClearMessage();
        }
    }


    #region 数据查询
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        this.txtCurrentPage.Text = "1";
        Dictionary<string, string> query = GetQuery();
        QueryData(query);
    }
    #region 重置
    protected void btnReSet_Click(object sender, EventArgs e)
    {
        ClearDispData();
    }
    #endregion
    public Dictionary<string, string> GetQuery()
    {
        string strScanContainerName = txtScan.Text.Trim();
        string strProcessNo = txtProcessNo.Text.Trim();
        string strContainerName = txtContainerName.Text.Trim();
        string strProductName = txtProductName.Text.Trim();
        string strStartDate = txtStartDate.Value.Trim();
        string strEndDate = txtEndDate.Value.Trim();

        Dictionary<string, string> result = new Dictionary<string, string>();
        result.Add("ScanContainerName", strScanContainerName);
        result.Add("ProcessNo", strProcessNo);
        result.Add("ContainerName", strContainerName);
        result.Add("ProductName", strProductName);
        result.Add("StartDate", strStartDate);
        result.Add("EndDate", strEndDate);
        Session[QueryWhere] = result;

        return result;
    }

    protected void txtScan_TextChanged(object sender, EventArgs e)
    {
        ShowStatusMessage("", true);

        try
        {
            string strScan = txtScan.Text.Trim();
            txtScan.Text = "";

            if(strScan != string.Empty)
            {
                Dictionary<string, string> para = new Dictionary<string, string>();
                para.Add("ScanContainerName", strScan);
                Session[QueryWhere] = para;
                txtCurrentPage.Text = "1";
                QueryData(para);
            }
        }
        catch(Exception ex)
        {
            ShowStatusMessage(ex.Message, false);
        }
    }

    public void QueryData(Dictionary<string, string> query)
    {
        ShowStatusMessage("", true);
        wgProduct.Rows.Clear();wgWorkFlow.Rows.Clear();wgSpec.Rows.Clear();
        uMESPagingDataDTO result = bll1.GetContainerChange(query, Convert.ToInt32(this.txtCurrentPage.Text), 10);
        this.ItemGrid.DataSource = result.DBTable;
        this.ItemGrid.DataBind();
        this.txtTotalPage.Text = result.PageCount;
        if (result.RowCount == "0")
        {
            this.txtCurrentPage.Text = "0";
        }
        lLabel1.Text = string.Format("第 {0} 页  共 {1} 页", this.txtCurrentPage.Text, this.txtTotalPage.Text);
        this.txtPage.Text = this.txtCurrentPage.Text;

       
    }

    protected void ClearDispData()
    {
       
        ItemGrid.Clear();
        wgProduct.Rows.Clear();
        wgWorkFlow.Clear();
        wgSpec.Clear();
        ResetQuery();

    }

    public void ResetQuery()
    {
        ShowStatusMessage("", true);

        Session[QueryWhere] = "";
        txtScan.Text = string.Empty;
        txtProcessNo.Text = string.Empty;
        txtContainerName.Text = string.Empty;
        txtProductName.Text = string.Empty;
        txtStartDate.Value = string.Empty;
        txtEndDate.Value = string.Empty;
        ItemGrid.Rows.Clear();

        this.txtTotalPage.Text = "";
        this.txtCurrentPage.Text = "";
        this.txtPage.Text = "";
        lLabel1.Text = "第  页  共  页";
    }
    #endregion

    #region 分页按钮
    public void lbtnFirst_Click(object sender, EventArgs e)
    {
        //this.txtCurrentPage.Text = "1";
        //Dictionary<string, string> query = GetQuery();
        //QueryData(query);
    }

    public void lbtnLast_Click(object sender, EventArgs e)
    {
        //this.txtCurrentPage.Text = this.txtTotalPage.Text;
        //Dictionary<string, string> query = GetQuery();
        //QueryData(query);
    }
    public void lbtnPrev_Click(object sender, EventArgs e)
    {
        //int currentPage = Convert.ToInt32(this.txtCurrentPage.Text);
        //if (currentPage > 1)
        //{
        //    currentPage = currentPage - 1;
        //}
        //this.txtCurrentPage.Text = currentPage.ToString();
        //Dictionary<string, string> query = GetQuery();
        //QueryData(query);
    }
    public void lbtnNext_Click(object sender, EventArgs e)
    {
        //int currentPage = Convert.ToInt32(this.txtCurrentPage.Text);
        //int totalPage = Convert.ToInt32(this.txtTotalPage.Text);
        //if (currentPage < totalPage)
        //{
        //    currentPage = currentPage + 1;
        //}
        //this.txtCurrentPage.Text = currentPage.ToString();
        //Dictionary<string, string> query = GetQuery();
        //QueryData(query);
    }

    public void btnGo_Click(object sender, EventArgs e)
    {
        //if (Convert.ToInt32(this.txtPage.Text) > 0 && Convert.ToInt32(this.txtPage.Text) <= Convert.ToInt32(this.txtTotalPage.Text))
        //{
        //    this.txtCurrentPage.Text = this.txtPage.Text;
        //    Dictionary<string, string> query = GetQuery();
        //    QueryData(query);
        //}
    }
    #endregion

    #region 提示信息
    /// <summary>
    /// 提示信息
    /// </summary>
    /// <param name="strMessage"></param>
    /// <param name="boolResult"></param>
    protected void ShowStatusMessage(string strMessage, Boolean boolResult)
    {
        //处理特殊字符 add:Wangjh
        strMessage = strMessage.Replace("\"", "");
        strMessage = strMessage.Replace("\r", "");
        strMessage = strMessage.Replace("\n", "");
        string strScript = "<script>ShowMessage(\"" + strMessage + "\", " + boolResult.ToString().ToLower() + ");</script>";
        //ClientScript.RegisterStartupScript(GetType(), "", strScript);
       
        Infragistics.WebUI.Shared.CallBackManager.AddScriptBlock(Page, WebAsyncRefreshPanel1, strScript);

    }
    #endregion

    #region 清除提示信息
    protected void ClearMessage()
    {
        string strScript = "<script>ShowMessage(\"" + "" + "\", 'true');</script>";
        LiteralControl child = new LiteralControl(strScript);
        WebAsyncRefreshPanel1.Controls.Add(child);
    }
    #endregion

    #region 选中批次行
    protected void ItemGrid_ActiveRowChange(object sender, RowEventArgs e)
    {
        ShowStatusMessage("", true);

        try
        {
            wgWorkFlow.Rows.Clear();
            wgSpec.Rows.Clear();
            UltraGridRow activeRow = ItemGrid.DisplayLayout.ActiveRow;
            Dictionary<string, string> para = new Dictionary<string, string>();
            para.Add("ProductID", activeRow.Cells.FromKey("productid").Value.ToString());
            DataTable dt = bll1.GetWorkflowInfoByProductForAscx(para);
            wgWorkFlow.DataSource = dt;
            wgWorkFlow.DataBind();

            DataTable productDt = bll1.GetProductWithOutSelf(activeRow.Cells.FromKey("ProductName").Text, activeRow.Cells.FromKey("ProductRevision").Text);
            wgProduct.DataSource = productDt;
            wgProduct.DataBind();

        }
        catch (Exception ex)
        {
            ShowStatusMessage(ex.Message, false);
        }
    }

    protected void wgWorkFlow_ActiveRowChange(object sender, RowEventArgs e)
    {
        ShowStatusMessage("", true);

        try
        {
            wgSpec.Rows.Clear();
            UltraGridRow activeRow = wgWorkFlow.DisplayLayout.ActiveRow;
            DataTable dt = bll1.GetStepInfoByWorkflowId(activeRow.Cells.FromKey("WorkFlowId").Value.ToString());
            dt.Columns.Add("SpecNameDisp");
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                string strSpecName = dt.Rows[i]["SpecName"].ToString();
                dt.Rows[i]["SpecNameDisp"] = common.GetSpecNameWithOutProdName(strSpecName);
            }
            wgSpec.DataSource = dt;
            wgSpec.DataBind();
        }
        catch (Exception ex)
        {
            ShowStatusMessage(ex.Message, false);
        }
    }


    #endregion

    #region 保存按钮
    protected void btnSave_Click(object sender, EventArgs e)
    {
        ShowStatusMessage("", true);

        try
        {
            
            UltraGridRow activeRow = ItemGrid.DisplayLayout.ActiveRow;
            UltraGridRow activeRow1 = wgWorkFlow.DisplayLayout.ActiveRow;
            UltraGridRow activeRow2 = wgSpec.DisplayLayout.ActiveRow;
            

            if (CheckData(true) == false)
            {
                return;
            }
           
            Dictionary<string, string> userInfo = Session["UserInfo"] as Dictionary<string, string>;
            var m_DataList = new List<ClientAPIEntity>();

            var dataEntity = new ClientAPIEntity();

            dataEntity.ClientDataTypeEnum = DataTypeEnum.ContainerField;
            dataEntity.ClientInputTypeEnum = InputTypeEnum.Details;
            dataEntity.ClientDataName = "Container";
            dataEntity.ClientDataValue = activeRow.Cells.FromKey("ContainerName").Value.ToString();
            dataEntity.ClientOtherValue = "";
            m_DataList.Add(dataEntity);

            dataEntity = new ClientAPIEntity();
            dataEntity.ClientDataName = "ToStep";
            dataEntity.ClientDataValue = activeRow2.Cells.FromKey("workflowstepname").Value.ToString(); ;
            dataEntity.ClientDataTypeEnum = DataTypeEnum.NamedSubentityField;
            m_DataList.Add(dataEntity);

            dataEntity = new ClientAPIEntity();
            dataEntity.ClientDataTypeEnum = DataTypeEnum.RevisionedObjectField;
            dataEntity.ClientInputTypeEnum = InputTypeEnum.CurrentStatusDetails;
            dataEntity.ClientDataName = "ToWorkflow";
            dataEntity.ClientDataValue = activeRow1.Cells.FromKey("workflowname2").Value.ToString();
            dataEntity.ClientDataVersion = activeRow1.Cells.FromKey("WorkFlowRevision").Value.ToString();
            m_DataList.Add(dataEntity);

            string strTxnDocName, strTxnName;
            strTxnDocName = "MoveNonStdDoc";
            strTxnName = "MoveNonStd";
            string strMessage = string.Empty;
            string strApiUserName = userInfo["EmployeeName"];
            string strApiPassword = userInfo["Password"];
            var api = new CamstarClientAPI(strApiUserName, strApiPassword);
            bool oResult  = api.RunTxnService(strTxnDocName, strTxnName, m_DataList,ref strMessage);

            //如何工艺有变更
            string workflowId = "";
            if (activeRow.Cells.FromKey("workflowid").Text != activeRow1.Cells.FromKey("WorkFlowId").Text) {
                workflowId = activeRow1.Cells.FromKey("WorkFlowId").Text;
            }

            ChangeContainerInfo("", activeRow.Cells.FromKey("ContainerID").Text, workflowId);

                if (oResult == true)
            {
                #region 记录日志
                var ml = new MESAuditLog();
                ml.ContainerName = activeRow.Cells.FromKey("ContainerName").Value.ToString(); ml.ContainerID = activeRow.Cells.FromKey("ContainerID").Value.ToString();
                ml.ParentID = ml.ContainerID; ml.ParentName = parentName;
                ml.CreateEmployeeID = userInfo["EmployeeID"];
                ml.BusinessName = businessName; ml.OperationType = 1;
                ml.Description = "批次调度:" + "调度到工艺:"+ activeRow1.Cells.FromKey("workflowname2").Text.ToString()+","+ activeRow1.Cells.FromKey("WorkFlowRevision").Text.ToString()+
                    "的工序:"+activeRow2.Cells.FromKey("workflowstepname").Text.ToString();
                common.SaveMESAuditLog(ml);
                #endregion

                ClearDispData();
                strMessage = "保存成功！";
                
            }
            ShowStatusMessage(strMessage, oResult);
        }
        catch (Exception ex)
        {
            ShowStatusMessage(ex.Message, false);
        }
    }
    /// <summary>
    /// 更改批次上的信息 add:Wangjh 20201124
    /// </summary>
    /// <param name="productid"></param>
    void ChangeContainerInfo(string productid,string containerId,string workflowId) {
        if (!string.IsNullOrWhiteSpace(productid))
        {
            OracleHelper.ExecuteDataByEntity(new ExcuteEntity("Container", ExcuteType.update)
            {
                ExcuteFileds = new List<FieldEntity>() {new FieldEntity("productid",productid,FieldType.Str)

            },
                strWhere = string.Format(" and containerid='{0}'", containerId)

            });

        }

        if (!string.IsNullOrWhiteSpace(workflowId))
        {
            //如若目标工艺没有预派工过，则需要置isaps和state字段,否则不用重置
            var temp = OracleHelper.QueryDataByEntity(new ExcuteEntity("dispatchinfo", ExcuteType.selectAll)
            {
                WhereFileds=new List<FieldEntity>() {new FieldEntity("containerid",containerId,FieldType.Str),new FieldEntity("workflowid",workflowId,FieldType.Str) }
            });

            int isasps = 0, state = 0;
            if (temp.Rows.Count > 0) {
                isasps = 1;
                if (temp.Select("parentid is not null").Length > 0) {
                    state = 1;
                }
            }
            //

            OracleHelper.ExecuteDataByEntity(new ExcuteEntity("Container", ExcuteType.update)
            {
                ExcuteFileds = new List<FieldEntity>() {new FieldEntity("isaps",isasps,FieldType.Str),new FieldEntity("state",state,FieldType.Str)

            },
                strWhere = string.Format(" and containerid='{0}'", containerId)

            });
        }

      }

    #region 数据验证
    protected Boolean CheckData(Boolean isValidateWorkflow)
    {
        Boolean result = true;

        UltraGridRow activeRow = ItemGrid.DisplayLayout.ActiveRow;
        if (activeRow == null)
        {
            ShowStatusMessage("请选择批次信息！",false);
            return false;
        }
        if (isValidateWorkflow) {
            UltraGridRow activeRow1 = wgWorkFlow.DisplayLayout.ActiveRow;
            if (activeRow1 == null)
            {
                ShowStatusMessage("请选择工艺路线！", false);
                return false;
            }

            UltraGridRow activeRow2 = wgSpec.DisplayLayout.ActiveRow;
            if (activeRow2 == null)
            {
                ShowStatusMessage("请选择工序！", false);
                return false;
            }
            string containerId = activeRow.Cells.FromKey("ContainerID").Text, workflowstepid = activeRow.Cells.FromKey("WorkflowStepID").Text;

            DataTable dt = OracleHelper.QueryDataByEntity(new ExcuteEntity("dispatchinfo", ExcuteType.selectAll)
            {
                strWhere = string.Format(" and parentid is not null and containerid='{0}' and WorkflowStepID='{1}' ", containerId, workflowstepid)
            });
            if (dt.Rows.Count > 0)
            {
                ShowStatusMessage("当前工序已经进行任务指派，无法调度！", false);
                return false;
            }
        }         


        return result;
    }
    #endregion

    //验证是否是数字
    public bool IsNumeric(string s)
    {
        bool bReturn = true;
        double result = 0;
        try
        {
            result = double.Parse(s);
        }
        catch
        {
            result = 0;
            bReturn = false;
        }
        return bReturn;
    }

    //验证是否是正整数
    public static bool IsInt(string inString)
    {
        Regex regex = new Regex("^[0-9]*[1-9][0-9]*$");
        return regex.IsMatch(inString.Trim());
    }
    #endregion

    /// <summary>
    /// 工艺文档查看
    /// </summary>
    /// <param name="wg"></param>
    /// <param name="UltraWebGrid"></param>
    /// <returns></returns>
    void SaveDocumentPoupData(UltraWebGrid wg)
    {
        ShowStatusMessage("", true);
        UltraGridRow uldr = wg.DisplayLayout.ActiveRow;
        if (uldr == null)
        {
            ShowStatusMessage("请选择批次记录!", false);
            //Infragistics.WebUI.Shared.CallBackManager.AddScriptBlock(Page, WebAsyncRefreshPanel1, "<script>alert('请选择批次记录')</script>");
            return;
        }

        DataTable poupDt = new DataTable();
        poupDt.Columns.Add("ProductID");
        poupDt.Columns.Add("WorkflowID"); poupDt.Columns.Add("ContainerID"); poupDt.Columns.Add("ContainerName");
        DataRow newRow = poupDt.NewRow();
        newRow["ProductID"] = uldr.Cells.FromKey("ProductID").Value.ToString();
        newRow["WorkflowID"] = uldr.Cells.FromKey("WorkflowID").Value.ToString(); newRow["ContainerID"] = uldr.Cells.FromKey("ContainerID").Text;
        newRow["ContainerName"] = uldr.Cells.FromKey("ContainerName").Text;
        poupDt.Rows.Add(newRow);
        Session.Add("ProcessDocument", poupDt);
        string script = string.Empty;//window.open(uMESSpecFinishConfirmPopupForm.aspx)

        script = "<script>window.showModalDialog('uMESDocumentViewPopupForm.aspx', '', 'dialogWidth: 700px; dialogHeight: 600px; status = no; center: Yes; resizable: NO; ')</script>";
        //ClientScript.RegisterStartupScript(GetType(), "", "<script>openmaterialapp()</script>");
        Infragistics.WebUI.Shared.CallBackManager.AddScriptBlock(Page, WebAsyncRefreshPanel1, script);

    }


    protected void Button1_Click(object sender, EventArgs e)
    {
        SaveDocumentPoupData(ItemGrid);
    }

    protected void btnSaveProduct_Click(object sender, EventArgs e)
    {
        try {
            if (CheckData(false) == false)
                return;
            UltraGridRow activeRow = ItemGrid.DisplayLayout.ActiveRow;
            //可能会更改产品
            string productId = "";
            foreach (UltraGridRow dr in wgProduct.Rows)
            {
                if (Convert.ToBoolean(dr.Cells.FromKey("ckSelect").Text) == false)
                    continue;

                productId = dr.Cells.FromKey("ProductId").Text;
            }
            if (string.IsNullOrWhiteSpace(productId)) {
                ShowStatusMessage("请选择产品！", false);
                return;
            }                    

            ChangeContainerInfo(productId, activeRow.Cells.FromKey("ContainerID").Text, "");

            #region 记录日志
            Dictionary<string, string> userInfo = Session["UserInfo"] as Dictionary<string, string>;
            var productRow = wgProduct.DisplayLayout.ActiveRow;
            var ml = new MESAuditLog();
            ml.ContainerName = activeRow.Cells.FromKey("ContainerName").Value.ToString(); ml.ContainerID = activeRow.Cells.FromKey("ContainerID").Value.ToString();
            ml.ParentID = ml.ContainerID; ml.ParentName = parentName;
            ml.CreateEmployeeID = userInfo["EmployeeID"];
            ml.BusinessName = businessName; ml.OperationType = 1;
            ml.Description = "批次调度:" + "调度到产品:" + productRow.Cells.FromKey("ProductName").Text+","+productRow.Cells.FromKey("ProductRevision").Text;
            common.SaveMESAuditLog(ml);
            #endregion

            ClearDispData();
            btnSearch_Click(null,null);
            ShowStatusMessage("调度成功！", true);
        


        } catch (Exception ex) {

            ShowStatusMessage(ex.Message, false);
        }
       

    }
}